package com.iplus.ydkf.ehome.common.net;

import com.alibaba.fastjson.JSONObject;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.BufferedSink;

/**
 * Created by lhtde on 2016/6/8.
 */
public class JsonRequestBody extends RequestBody {
    private JSONObject jsonObject;
    private static JsonRequestBody jsonRequestBody;

    public JsonRequestBody() {

    }

    public static JsonRequestBody create() {
        if (jsonRequestBody == null)
            jsonRequestBody = new JsonRequestBody();
        return jsonRequestBody;
    }

    public RequestBody build() {
        return jsonRequestBody.getInstance(jsonObject);
    }

    @Override
    public MediaType contentType() {
        return MediaType.parse("application/json");
    }

    public static MediaType getContentType() {
        return MediaType.parse("application/json");
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {

    }

    public JsonRequestBody(JSONObject jsonObject) {
        this.jsonObject = jsonObject;
    }

    public static RequestBody getInstance(JSONObject jsonObject) {
        return JsonRequestBody.create(getContentType(), jsonObject.toJSONString());
    }

    public JsonRequestBody put(String key, Object value) {
        if (jsonObject == null) jsonObject = new JSONObject();
        jsonObject.put(key, value);
        return jsonRequestBody;
    }

    public String toString() {
        if (jsonObject == null) jsonObject = new JSONObject();
        return jsonObject.toJSONString();
    }

    public RequestBody toRequestBody() {
        if (jsonObject == null) jsonObject = new JSONObject();
        return JsonRequestBody.create(contentType(), jsonObject.toJSONString());
    }
}
